import Link from 'next/link';
import { useState } from 'react';
import { useRouter } from 'next/router';
import type { MenuProps } from 'antd';
import { Button, Avatar, Dropdown, message } from 'antd';
import { LoginOutlined, HomeOutlined } from '@ant-design/icons';

import Login from '@/components/login';
import userStore from '@/store/userStore';
import requestInstance from '@/service/fetch';

import { navs } from './config';

import Styles from './index.module.scss';

const Navbar = () => {
  const { pathname, push } = useRouter();

  const [isShowLogin, setIsShowLogin] = useState(false);

  const [{ userId, avatar }, setUserInfo] = userStore((state) => [
    state.userInfo,
    state.setUserInfo,
  ]);

  const handleGoToEditorPage = () => {
    if (userId) {
      // 已经登录了
      push('/editor/new');
    } else {
      // 未登录
      message.warning('清先登录');
    }
  };

  const handleLogin = () => {
    setIsShowLogin(true);
  };

  const handleClose = () => {
    setIsShowLogin(false);
  };

  const handleMenuClick: MenuProps['onClick'] = (e) => {
    if (e.key === 'homePage') {
      handleGoToPersonalPage();
    }

    if (e.key === 'logOut') {
      handleLogOut();
    }
  };

  const handleGoToPersonalPage = () => {
    // 动态匹配 userId 来匹配个人主页
    push(`/user/${userId}`);
  };

  const handleLogOut = async () => {
    const result: any = await requestInstance.post('/api/user/logout');

    if (result.code === 200) {
      message.success(result.message || '退出登录成功');
      setUserInfo({});
    }
  };

  const items: MenuProps['items'] = [
    {
      key: 'homePage',
      label: (
        <>
          <HomeOutlined />
          &nbsp; 个人主页
        </>
      ),
    },
    {
      key: 'logOut',
      label: (
        <>
          <LoginOutlined />
          &nbsp; 退出系统
        </>
      ),
    },
  ];

  return (
    <div className={Styles.navbar}>
      <section className={Styles.logoArea}>BLOG-C</section>
      <section className={Styles.linkArea}>
        {navs.map(({ label, value }) => {
          return (
            <Link key={label} href={value}>
              <div
                className={`${Styles['linkArea--link']} ${
                  pathname === value ? Styles.active : ''
                }`}
              >
                {label}
              </div>
            </Link>
          );
        })}
      </section>
      <section className={Styles.operationArea}>
        <Button onClick={handleGoToEditorPage}>写文章</Button>

        {userId ? (
          <Dropdown
            menu={{ items, onClick: handleMenuClick }}
            placement="bottomLeft"
          >
            <Avatar src={avatar} size={32} />
          </Dropdown>
        ) : (
          <Button type="primary" onClick={handleLogin}>
            登录
          </Button>
        )}
      </section>
      <Login isShow={isShowLogin} onClose={handleClose} />
    </div>
  );
};

export default Navbar;
